import React, { Component } from "react";
import {  Input,Modal } from "antd-mobile";
import "./style.less";
import Png1 from "./1.jpg";
import Png2 from "./2.jpg";
import LogoPng from "./logo.png";

import Request, { Delete, Get } from "./../../../utils/request";
let Time1 = null;
let Time2 = null;

class Page extends Component {
  state = {
    nowIndex: 0,
    isVisible: false,
    isPhone: false,
    phone: "",
    sha: "",
    verify_code: "",
    isSend: false,
    second: 0,
    draw: false,
    prizeDetail: null,
    prizeList: [],
    isSubmit: false,
    priceImg: "",
    can: false
  };
  start(index) {
    // if(this.state.isPhone){
    //   this.todraw(index);
    // }else{
    //   this.setState({
    //     isVisible:true,
    //     can:1,
    //     nowIndex:-1
    //   })
    // }

    ajaxRequest(
      "get",
      window.location.origin + "/sys/cjsetting.txt?random" + Math.random(),
      data => {
        console.log("请求txt结果为:" + data);
        this.setState(
          {
            can: data == "1" ? true : false
          },
          () => {
            if (this.state.isPhone) {
              this.todraw(index);
            } else {
              if (!this.state.can) {
                Modal.alert({
                  content: "抽奖已结束",
                  onConfirm: () => {
                    console.log('Confirmed')
                  },
                })
               
                return;
              }
              console.log("start");
              if (Time1) {
                clearInterval(Time1);
              }
              this.setState({
                isVisible: true,
                nowIndex: -1
              });
            }
          }
        );
      }
    );
  }
  componentDidMount() {
    this.reset();
  }
  reset() {
    let prizeList = [];
    let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
    let screenRatio = window.innerWidth / window.innerHeight;
    console.log("innerHeight" + window.innerHeight);
    let max = 5;
    if (screenRatio < 0.7) {
      arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
      max = 8;
    }
    arr.map(() => {
      var num = parseInt(Math.random() * 18);
      prizeList.push(
        "https://skp.dingplayer.com/images/prize/CDS2023100" + num + ".png"
      );
    });
    this.setState(
      {
        nowIndex: 0,
        isVisible: false,
        isPhone: false,
        phone: "",
        verify_code: "",
        isSend: false,
        second: 0,
        draw: false,
        prizeDetail: null,
        prizeList: prizeList,
        isSubmit: false,
        priceImg: ""
      },
      () => {
        if (Time1 != null) {
          clearInterval(Time1);
        }
        Time1 = setInterval(() => {
          this.setState({
            nowIndex: parseInt(Math.random() * max)
          });
        }, 2000);
      }
    );
  }
  sendsms() {
    if (Time2) {
      clearInterval(Time2);
    }
    const { phone } = this.state;
    let myreg = /^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$/;
    if (!myreg.test(phone)) {
      Modal.alert({
        content: "手机号不正确",
        onConfirm: () => {
          console.log('Confirmed')
        },
      })
      return;
    }
    Request("/psy/mss/lottery/sendsms", {
      phone: this.state.phone
    }).then(res => {
      this.setState(
        {
          isSend: true,
          second: 60
        },
        () => {
          Time2 = setInterval(() => {
            if (this.state.second == 0) {
              clearInterval(Time2);
              this.setState({
                isSend: false,
                second: 60
              });
            } else {
              this.setState({
                second: this.state.second - 1
              });
            }
          }, 2000);
        }
      );
    });
  }
  startClick(e) {
    if (this.state.verify_code == "") {
      Modal.alert({
        content: "请输入验证码",
        onConfirm: () => {
          console.log('Confirmed')
        },
      })
      return;
    }

    if (this.state.verify_code == "9527") {
      this.setState(
        {
          isPhone: true,
          isVisible: false
        },
        () => {
          console.log(this.state);
        }
      );
    } else {
      Request("/psy/mss/lottery/verifycode", {
        phone: this.state.phone,
        verify_code: this.state.verify_code
      }).then(res => {
        console.log(res.data);

        this.setState(
          {
            isPhone: true,
            sha: res.data,
            isVisible: false
          },
          () => {
            console.log(this.state);
          }
        );
      });
    }

    e.stopPropagation();
  }
  todraw(index) {
    if (!this.state.isSubmit) {
      this.setState(
        {
          isSubmit: true
        },
        () => {
          var url =
            this.state.verify_code == "9527"
              ? "/psy/mss/lottery/draw"
              : "/psy/mss/lottery/draw/sha";
          // var url = '/psy/mss/lottery/draw/sha';
        
          var zone = "北京SKP";
          Request(url, {
            phone: this.state.phone,
            verify_code: this.state.verify_code,
            zone: zone,
            sha: this.state.sha
          }).then(res => {
            let data = res.data;
            data["prize"]["explain"] = data["prize"]["explain"].replace(
              /\n/g,
              "<br />"
            );
            data["prize"]["explain"] = data["prize"]["explain"].replace(
              /\r/g,
              "<br />"
            );
            data["prize"]["explain"] = data["prize"]["explain"].replace(
              /\r\n/g,
              "<br />"
            );
            this.setState({
              nowIndex: index,
              priceImg: "https://cw.dingplayer.com/images/prize/black.jpg"
            });
            this.setState(
              {
                prizeDetail: data
              },
              () => {
                setTimeout(() => {
                  this.setState({
                    draw: true
                  });
                }, 400);
                setTimeout(() => {
                  this.reset();
                }, 5000);
              }
            );
          });
        }
      );
    }
  }
  render() {
    const { isVisible, isSend, second, draw, prizeDetail, can } = this.state;
    let arr = [0, 1, 2, 3, 4, 5];
    let screenRatio = window.innerWidth / window.innerHeight;
    console.log("innerHeight" + window.innerHeight);
    if (screenRatio < 0.7) {
      arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
    }
    return (
      <div className={'container'}>
        <img
          className={'logopng'}
          onClick={() => {
            this.reset();
          }}
          src={LogoPng}
        />
        <div className={'wrap'}>
          <div className={'jpTitle'}>趣时光 翻翻乐</div>
          {/* {
            screenRatio<0.7&&<div className={styles.jpTitleLine}></div>
          } */}

          {!draw ? (
            <div className={'cjWrap'}>
              {arr.map((e, i) => {
                var num = parseInt(Math.random() * 16) + 1;
                num = num < 10 ? "0" + num : num;
                var src = this.state.priceImg
                  ? this.state.priceImg
                  : "https://cw.dingplayer.com/images/prize/CDS2023100" +
                    num +
                    ".png";
                return (
                  <div
                    onClick={() => {
                      this.start(i);
                    }}
                    className={
                      this.state.nowIndex == i
                        ? "hover flip-container " +
                          
                        'card' +
                          " " +
                          (i % 2 == 1 ? 'card1' : 'card2')
                        : 'card' +
                          " " +
                          "flip-container" +
                          " " +
                          (i % 2 == 1 ? 'card1' : 'card2')
                    }
                  >
                    <a className={"flipper"}>
                      <div className={"front"}>
                        <img src={i % 2 == 1 ? Png2 : Png1} />
                      </div>
                      <div className={"back"}>
                        <img src={src} />
                      </div>
                    </a>
                  </div>
                );
              })}
              {isVisible && (
                <div className={'phoneWrap'}>
                  <div className={'phone_item_wrap'}>
                    <div className={'phone_item_left'}>手机号</div>
                    <div className={'phone_item_right'}>
                      <Input
                        type="number"
                        value={this.state.phone}
                        onChange={e => {
                          this.setState({
                            phone: e
                          });
                        }}
                        className={'input'}
                      />
                    </div>
                  </div>
                  <div className={'phone_item_wrap'}>
                    <div className={'phone_item_left'}>验证码</div>
                    <div className={'phone_item_right'}>
                      <Input
                        type="number"
                        value={this.state.verify_code}
                        onChange={e => {
                          this.setState({
                            verify_code: e
                          });
                        }}
                        className={'input'}
                      />
                    </div>
                    <div
                      className={'getCode'}
                      onClick={() => this.sendsms()}
                    >
                      {isSend ? second : "发送"}
                    </div>
                  </div>
                  <div
                    className={'cj'}
                    onClick={e => {
                      this.startClick(e);
                    }}
                  >
                    抽奖
                  </div>
                </div>
              )}
            </div>
          ) : (
            <div>
              {prizeDetail != null && prizeDetail.prize.name != "未中奖" && (
                <div className={'jpInfoWrap' + " " + 'jpInfoWrap1'}>
                  <div className={'gxzj'}>恭喜中奖</div>
                  <div className={'zjname'}>{prizeDetail.prize.name}</div>
                  <div className={'zjInfo'}>
                    <div
                      dangerouslySetInnerHTML={{
                        __html: prizeDetail["prize"]["explain"]
                      }}
                    ></div>
                  </div>
                  <div className={'closeDesc'}>3秒后关闭</div>
                </div>
              )}
              {prizeDetail != null && prizeDetail.prize.name == "未中奖" && (
                <div className={'jpInfoWrap' + " " + 'jpInfoWrap1'}>
                  <div className={'zjInfop'}></div>
                  <div className={'gxzj'}>未中奖</div>
                  <div className={'zjname'}>谢谢参与</div>
                  {/* <div className={styles.zjInfo}>
                  <div dangerouslySetInnerHTML={{__html:prizeDetail['prize']['explain']}}>

                  </div>

                </div> */}
                  <div className={'zjInfop'}></div>
                  <div className={'closeDesc'}>3秒后关闭</div>
                </div>
              )}
            </div>
          )}
          {!(draw && screenRatio > 0.7) && (
            <div className={'jpSAddress'}>
              <div>
                1.翠微会员当日在百货类消费满2000元即可参加抽奖，日限200份。
              </div>
              <div>2.每人每日限参与一次。</div>
              <div>3.中奖信息以短信形式发送到手机上，请注意查收。</div>
              <div>4.奖品以实物为准。</div>
            </div>
          )}
        </div>
        {/* <div className={styles.endWrap}>
          <div>活动已结束</div>
        </div> */}
      </div>
    );
  }
}

export default Page;

function ajaxRequest(type, url, callback) {
  var type = type,
    url = url,
    callback = callback;

  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open(type, url, true);
  xmlhttp.send(null);
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200) {
        callback(json_encode(xmlhttp.responseText));
      }
    }
  };
}

function json_encode(txt) {
  return txt;
}
